/*
 * Copyright 2018-present KunMinX
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.nsgf.library.data.repository;

import android.os.Build;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.nsgf.library.data.api.APIs;
import com.nsgf.library.data.api.AccountService;
import com.nsgf.library.data.bean.ClockInBean;
import com.nsgf.library.data.bean.MessageBean;
import com.nsgf.library.data.bean.User;
import com.nsgf.library.data.bean.UserDataBean;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.bean.WeatherBean;
import com.nsgf.library.data.bean.WorkOrderBean;
import com.nsgf.library.data.bean.WorkOrderDetailBean;
import com.nsgf.library.data.response.DataResult;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.data.response.ResultSource;
import com.nsgf.library.domain.request.AsyncTask;
import com.nsgf.library.domain.request.BaseHttpObserver;
import com.nsgf.library.domain.request.HttpOnNextListener;
import com.nsgf.library.utils.SysUtil;
import com.nsgf.library.utils.ToastUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Create by GC at 24/10/29
 */
public class DataRepository {

    private static final DataRepository S_REQUEST_MANAGER = new DataRepository();

    // 获取到请求类型（MediaType）
    private static MediaType mediaType = MediaType.parse("application/json;charset=UTF-8");

    private DataRepository() {
    }

    public static DataRepository getInstance() {
        return S_REQUEST_MANAGER;
    }

    private static Retrofit retrofitCallAdapter;
    private static Retrofit retrofitCallAdapterAdmin;
    private static Retrofit retrofitCallAdapterNotToken;

    public static Retrofit getRetrofitInstance() {
        if (retrofitCallAdapter == null) {

            Interceptor headerInterceptor = a -> {
                Request originalRequest = a.request();
                Request.Builder requestBuilder = originalRequest.newBuilder()
//                        .addHeader("Accept-Encoding", "gzip")
                        .addHeader("Accept", "application/json")
                        .addHeader("version", SysUtil.getAppVersion())
                        .addHeader("source", "android")
                        .addHeader("User-Agent", "android")
                        .addHeader("pda_model", Build.MODEL)
                        .addHeader("terminal", "31")
                        .addHeader("Authorization",UserInfo.getInstance().getTokenValue())
                        .addHeader("sys_version", Build.VERSION.RELEASE)
                        .addHeader("Content-Type", "application/json; charset=UTF-8")
                        .method(originalRequest.method(), originalRequest.body());
                Request request = requestBuilder.build();
                return a.proceed(request);
            };
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(15, TimeUnit.SECONDS)
                    .readTimeout(15, TimeUnit.SECONDS)
                    .writeTimeout(15, TimeUnit.SECONDS)
                    .addInterceptor(logging)
                    .addInterceptor(headerInterceptor)
                    .build();

            retrofitCallAdapter = new Retrofit.Builder()
                    .baseUrl(APIs.BASE_URL)
                    .client(client)
                    .addConverterFactory(MyGsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
        }
        return retrofitCallAdapter;
    }
    public static Retrofit getRetrofitNotTokenInstance() {
        if (retrofitCallAdapterNotToken == null) {

            Interceptor headerInterceptor = a -> {
                Request originalRequest = a.request();
                Request.Builder requestBuilder = originalRequest.newBuilder()
//                        .addHeader("Accept-Encoding", "gzip")
                        .addHeader("Accept", "application/json")
                        .addHeader("version", SysUtil.getAppVersion())
                        .addHeader("source", "android")
                        .addHeader("User-Agent", "android")
                        .addHeader("pda_model", Build.MODEL)
                        .addHeader("terminal", "31")
                        .addHeader("sys_version", Build.VERSION.RELEASE)
                        .addHeader("Content-Type", "application/json; charset=UTF-8")
                        .method(originalRequest.method(), originalRequest.body());
                Request request = requestBuilder.build();
                return a.proceed(request);
            };
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(15, TimeUnit.SECONDS)
                    .readTimeout(15, TimeUnit.SECONDS)
                    .writeTimeout(15, TimeUnit.SECONDS)
                    .addInterceptor(logging)
                    .addInterceptor(headerInterceptor)
                    .build();

            retrofitCallAdapterNotToken = new Retrofit.Builder()
                    .baseUrl(APIs.BASE_URL)
                    .client(client)
                    .addConverterFactory(MyGsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
        }
        return retrofitCallAdapterNotToken;
    }

    public static Retrofit getAdminRetrofitInstance() {
        if (retrofitCallAdapterAdmin == null) {

            Interceptor headerInterceptor = a -> {
                Request originalRequest = a.request();
                Request.Builder requestBuilder = originalRequest.newBuilder()
//                        .addHeader("Accept-Encoding", "gzip")
                        .addHeader("Accept", "application/json")
                        .addHeader("version", SysUtil.getAppVersion())
                        .addHeader("source", "android")
                        .addHeader("User-Agent", "android")
                        .addHeader("pda_model", Build.MODEL)
                        .addHeader("terminal", "31")
                        .addHeader("Authorization",UserInfo.getInstance().getTokenValue())
                        .addHeader("sys_version", Build.VERSION.RELEASE)
                        .addHeader("Content-Type", "application/json; charset=UTF-8")
                        .method(originalRequest.method(), originalRequest.body());
                Request request = requestBuilder.build();
                return a.proceed(request);
            };
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(15, TimeUnit.SECONDS)
                    .readTimeout(15, TimeUnit.SECONDS)
                    .writeTimeout(15, TimeUnit.SECONDS)
                    .addInterceptor(logging)
                    .addInterceptor(headerInterceptor)
                    .build();

            retrofitCallAdapterAdmin = new Retrofit.Builder()
                    .baseUrl(APIs.BASE_URL_ADMIN)
                    .client(client)
                    .addConverterFactory(MyGsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
        }
        return retrofitCallAdapterAdmin;
    }


    public <T> void subscribe(Observable<T> o, DisposableObserver<T> s) {
        o.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
//                .retry(RETRY_COUNT)
                .subscribe(s);
    }


    private final Retrofit retrofit;

    {
        Interceptor headerInterceptor = a -> {
            Request originalRequest = a.request();
            Request.Builder requestBuilder = originalRequest.newBuilder()
                    .addHeader("Accept-Encoding", "gzip")
                    .addHeader("Accept", "application/json")
//                .addHeader("version", SysUtil.getAppVersion())
                    .addHeader("source", "android")
                    .addHeader("User-Agent", "android")
                    .addHeader("pda_model", Build.MODEL)
                    .addHeader(UserInfo.getInstance().getTokenName(), UserInfo.getInstance().getTokenValue())
                    .addHeader("sys_version", Build.VERSION.RELEASE)
                    .addHeader("Content-Type", "application/json; charset=utf-8")
                    .method(originalRequest.method(), originalRequest.body());
            Request request = requestBuilder.build();
            return a.proceed(request);
        };
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .addInterceptor(logging)
                .addInterceptor(headerInterceptor)
                .build();


        retrofit = new Retrofit.Builder()
                .baseUrl(APIs.BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

}
